<?php

namespace App\Http\Controllers\Api\V1;

use App\Models\User;
use Illuminate\Support\Facades\Cache;
use App\Services\ApplyGoldCoinWithdraw\ApplyGoldCoinWithdraw;
use App\Services\ApplyGoldCoinWithdraw\ApplyGoldCoinWithdrawRequest;

class WithdrawsController extends Controller
{
	public function store()
    {
    	$lock = Cache::lock('withdraw', 30);

    	try {

    		if (! $lock->get()) fail('太快了，请再试一次');

    		$request = app(ApplyGoldCoinWithdrawRequest::class);

    		$user = $request->user();

    		need_paycode($user);

		    app(ApplyGoldCoinWithdraw::class, [
			    'user' => $user,
			    'coins' => $request->coins,
			    'payCode' => $request->pay_code,
		    ])->apply();

		    $user->resetPayCodeTry();

	    } finally {
    		$lock->release();
	    }

	    return response(null, 204);
    }

    public function free()
    {
	    /**
	     * @var User $user
	     */
	    $user = request()->user();

    	return response()->json([
		    'gold_free_withdraw_quota' => $user->freeWithdrawQuota(),
	    ]);
    }
}
